const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;

// 存储留言的数组，实际应用中应使用数据库
let messages = [];

app.use(bodyParser.json());
app.use(express.static('public')); // 用于托管前端静态页面

// API获取所有留言
app.get('/api/messages', (req, res) => {
  res.json(messages);
});

let messageId = 0;

app.post('/api/messages', (req, res) => {
  const { name, content } = req.body;
  if (!name || !content) {
    return res.status(400).json({ error: "Name and content are required." });
  }
  
  const message = {
    id: ++messageId,
    name: name,       // 存储姓名
    content: content  // 存储留言内容
  };
  
  messages.push(message);
  res.status(201).json(message);
});

app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});
